package com.allprs.common.utils.http;


import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.util.*;

/**
 * http请求工具类
 * @Author: wjf
 * @Date: 2021/9/22 14:30
 */
@Component
public class HttpUtil {

    private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

    private static String HTTP_CONNECT_TIMEOUT;

    private static String HTTP_REQUEST_CONNECT_TIMEOUT;

    private static String HTTP_SOCKET_CONNECT_TIMEOUT;

    @Value("${HTTP_CONNECT_TIMEOUT}")
    public void setHttpConnectTimeout(String httpConnectTimeout) {

        HttpUtil.HTTP_CONNECT_TIMEOUT = httpConnectTimeout;
    }

    @Value("${HTTP_REQUEST_CONNECT_TIMEOUT}")
    public void setHttpRequestConnectTimeout(String httpRequestConnectTimeout) {
        HttpUtil.HTTP_REQUEST_CONNECT_TIMEOUT = httpRequestConnectTimeout;
    }

    @Value("${HTTP_SOCKET_CONNECT_TIMEOUT}")
    public void setHttpSocketConnectTimeout(String httpSocketConnectTimeout) {
        HttpUtil.HTTP_SOCKET_CONNECT_TIMEOUT = httpSocketConnectTimeout;
    }

    /**
     * 发送get请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);

            //设置请求超时时间
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpGet.setConfig(config);

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }


    /**
     * 发送带请求头的get
     *
     * @param url
     * @param param
     * @param headMap
     * @return
     */
    public static String doGet(String url, Map<String, String> param, Map<String, String> headMap) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpGet.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpGet.setHeader(key, headMap.get(key));
                }
            }
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {

                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * @param url
     * @return
     */
    public static String doGet(String url) {
        return doGet(url, null);
    }

    /**
     * @param url
     * @param json
     * @return
     */
    public static String doGetJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpGetWithEntity httpGetWithEntity  = new HttpGetWithEntity (url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpGetWithEntity.setConfig(config);
            // 创建请求内容
            HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpGetWithEntity.setEntity(httpEntity);
            // 执行http请求
            response = httpClient.execute(httpGetWithEntity);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    public static String doGetJson(String url, String json,Map<String, String> headMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpGetWithEntity httpGetWithEntity  = new HttpGetWithEntity (url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpGetWithEntity.setConfig(config);

            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpGetWithEntity.setHeader(key, headMap.get(key));
                }
            }

            // 创建请求内容
            HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);

            httpGetWithEntity.setEntity(httpEntity);
            // 执行http请求
            response = httpClient.execute(httpGetWithEntity);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * post请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPost.setConfig(config);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                //记录接口日志

                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * 发送带请求头的post请求
     *
     * @param url
     * @param param
     * @param headMap
     * @return
     */
    public static String doPost(String url, Map<String, String> param, Map<String, String> headMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPost.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpPost.setHeader(key, headMap.get(key));
                }
            }
            // 创建参数列表
            if (param != null && !param.isEmpty()) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");

        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                //记录接口日志
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * @param url
     * @return
     */
    public static String doPost(String url) {
        return doPost(url, null);
    }

    /**
     * @param url
     * @param json
     * @return
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPost.setConfig(config);
            // 创建请求内容s
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    public static String doPostJson(String url, String json, Map<String, String> headMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPost.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpPost.setHeader(key, headMap.get(key));
                }
            }
            // 创建请求内容s
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }

    /**
     * 发送delete请求
     *
     * @param url
     * @param param
     * @return
     */
    public static String doDelete(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpDelete.setConfig(config);
            // 创建参数列表
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            httpDelete.setURI(uri);
            response = httpClient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }

    /**
     * 发送带请求头的delete请求
     *
     * @param url
     * @param param
     * @param headMap
     * @return
     */
    public static String doDelete(String url, Map<String, String> param, Map<String, String> headMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            HttpDelete httpDelete = new HttpDelete(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpDelete.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpDelete.setHeader(key, headMap.get(key));
                }
            }
            // 创建参数列表
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            httpDelete.setURI(uri);
            response = httpClient.execute(httpDelete);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }

    public static String doDeleteJson(String url,String json,Map<String, String> headMap) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Delete请求
            HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpDelete.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpDelete.setHeader(key, headMap.get(key));
                }
            }


            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpDelete.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpDelete);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }

        return resultString;
    }

    public static String doDelete(String url) {
        String s = doDelete(url, null);
        return s;
    }


    /**
     * 功能描述 (发送put请求带参数)
     *
     * @param *     @param url
     * @param param
     * @return
     * @author qqg
     * @date
     */
    public static String doPut(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http PUT请求
            HttpPut httpPut = new HttpPut(uri);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPut.setConfig(config);
            // 执行请求
            response = httpclient.execute(httpPut);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * 功能描述 (发送put请求带参数，参数为json数据)
     *
     * @param *    @param url
     * @param json
     * @return
     * @author qqg
     * @date
     */
    public static String doPut(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPut httpPut = new HttpPut(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPut.setConfig(config);
            // 创建请求内容s
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPut.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPut);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }

    /**
     * 功能描述 (发送put请求带参数，带请求头)
     *
     * @param *     @param url
     * @param param
     * @return
     * @author qqg
     * @date
     */
    public static String doPut(String url, Map<String, String> param, Map<String, String> headMap) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http PUT请求
            HttpPut httpPut = new HttpPut(uri);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(Integer.parseInt(HTTP_CONNECT_TIMEOUT)).
                    setConnectionRequestTimeout(Integer.parseInt(HTTP_REQUEST_CONNECT_TIMEOUT)).
                    setSocketTimeout(Integer.parseInt(HTTP_SOCKET_CONNECT_TIMEOUT)).build();
            httpPut.setConfig(config);
            if (headMap != null && !headMap.isEmpty()) {
                Set<String> keys = headMap.keySet();
                for (String key : keys) {
                    httpPut.setHeader(key, headMap.get(key));
                }
            }
            // 执行请求
            response = httpclient.execute(httpPut);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
        return resultString;
    }


}
